#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <cstring>
#include <arpa/inet.h>

int main(int argc, char *args[])
{
    if (argc != 3)
    {
        std::cout << "./UdpClient serverip serverport" << std::endl;
        exit(0);
    }
    std::string server_ip = args[1];
    uint16_t port = std::stoi(args[2]);
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    while (1)
    {
        std::string line;
        std::cout << "Please Enter# ";
        std::getline(std::cin, line);

        int n = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n > 0)
        {
            struct sockaddr_in temp;
            char buffer[1024];
            socklen_t len = sizeof(temp);
            int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
            else
            {
                std::cout << "recvfrom error" << std::endl;
                break;
            }
        }
        else
        {
            std::cout<<"sendto error"<<std::endl;
            break;
        }
    }
    ::close(sockfd);

    return 0;
}